package com.ssps.shiro.service.iml;

import com.ssps.entity.*;
import com.ssps.mapper.RoleMapper;
import com.ssps.mapper.UserRoleMapper;
import com.ssps.shiro.service.Tenant2AuthService;
import com.ssps.mapper.UserInfoMapper;
import com.ssps.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: peng
 */
@Transactional
@Service
public class Teant2AuthServiceImpl implements Tenant2AuthService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserInfoMapper userInfoMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    RoleMapper roleMapper;
    @Override
    public User selectByPhoneAndPassword(String phone) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andPhoneEqualTo(phone);

        List<User> users = userMapper.selectByExample(userExample);
        return users.isEmpty() ? null : users.get(0);
    }

    @Override
    public UserInfo selectByUid(Integer uid) {
        UserInfoExample userInfoExample = new UserInfoExample();
        UserInfoExample.Criteria userInfoExampleCriteria = userInfoExample.createCriteria();
        userInfoExampleCriteria.andUidEqualTo(uid);
        return userInfoMapper.selectByExample(userInfoExample).isEmpty() ? null : userInfoMapper.selectByExample(userInfoExample).get(0);
    }

    @Override
    public String getRole(User user) {
        UserRoleExample userRoleExample = new UserRoleExample();
        UserRoleExample.Criteria userRoleExampleCriteria = userRoleExample.createCriteria();
        userRoleExampleCriteria.andUidEqualTo(user.getUid());

        List<UserRoleKey> userRoleKeys = userRoleMapper.selectByExample(userRoleExample);

        UserRoleKey userRoleKey = userRoleKeys.get(0);
        Role role = roleMapper.selectByPrimaryKey(userRoleKey.getRid());

        return role.getRname();
    }
}
